<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/19/0019
 * Time: 18:05
 */

namespace App\Service;


use App\Models\GoodCategory;

class CategoryService
{
    protected $model;

    public function __construct(){
        $this->model = new GoodCategory();
    }

    //获取分类信息
    public  function getCatetree($id=0){

        //获取所有信息
        $data = $this->model->all()->where('status','!=','0');
        $list = $this->getThree($data,$id,1,false);
        return  $list;
    }


//获取某个分类的子分类
    public function getChild($id)
    {
        //先获取所有的分类信息
        $data = $this->model->all()->where('status','!=','0');
        //在对获取的信息进行格式化
        $list = $this->getThree($data,$id,1,false);
        foreach ($list as $key => $value) {
            $tree[]=$value['id'];
        }
        return $tree;
    }

    //格式化分类信息
    public function getThree($data,$id=0,$lev=1,$iscache=true)
    {
        static $list = [];
        //根据参数决定是否需要重置
        if(!$iscache){
            $list= [];
        }
        foreach ($data as $key => $value) {
            if($value['parent_id']==$id){
                $value['lev']=$lev;
                $list[]=$value;
                //使用递归的方式获取分类下的子分类
                $this->getThree($data,$value['id'],$lev+1);
            }
        }
        return $list;
    }
}